/**
 * 数据表格、表单处理
 * 基于layui 紧跟最新
 * @author kaige
 * @date 2022-3-14 update 2023-08-22
 * @version 2.0.0
 **/
layui.define(['layer', 'form', 'table', 'laytpl', 'element', 'tableSelect', 'xmSelect'], function (exports) {
    var MOD_NAME = 'kaige', $ = layui.jquery, form = layui.form, table = layui.table, layer = layui.layer, laytpl = layui.laytpl, element = layui.element, tableSelect = layui.tableSelect;
    var xmSelect = layui.xmSelect;
    kaige = function () { };
    // 封装递归方法--子项是否选中
    function treeSelected(tree, value) {
        for (var key in tree) {
            tree[key]['value'] = tree[key].id;
            tree[key]['selected'] = strIn(tree[key].id.toString(), value);
            if (tree[key].children && tree[key].children.length > 0) {
                // tree[key]['disabled'] = true;
                treeSelected(tree[key].children, value);
            }
        };
        return tree;
    }
    kaige.prototype.config = function () {
        return {
            form: {
                opentype: 'layer.open', // layer.open | dom 传入接收的ID
                data: {},
                area: ['700px', '420px'],
                offset: 'auto',
                title: false,
                maxmin: false,
                resize: true,
                overflow: true, //默认开启
                callbefore: function () { }, //窗体成功打开后处理回调，在监听表单前
                callback: function (res) { },//表单提交后回调
                postbefore: function (d) {
                    //提交前表单处理回调，改变表单上传值
                    return d;
                },
            },
            del: {
                callback: function (res) { },
            },
            viewimage: {
                maxwidth: '500px',
                maxheight: '500px',
            },
            table: {
                height: 'full-30',
                defaultToolbar: ['filter'],
                page: {
                    layout: ['prev', 'page', 'next', 'limit', 'count', 'skip', 'refresh'],
                    groups: 8,
                    limits: [20, 50, 100, 150, 200, 300, 500, 1000]
                },
                limit: '20',
                method: 'GET',
                // nosign: false, //是否不要签名（默认是签名的）,true=不要签
                done: function (res, curr, count) { }
            },
            xmSelect: {
                theme: {
                    color: '#0081ff',
                },
                filterable: true,
                remoteSearch: true,
                tree: {}
            }
        };
    }

    /**新增或编辑，通用处理方法 tpl*/
    kaige.prototype.form = function (e) {
        var t = this;
        e = $.extend(t.config().form, e);
        if (e.id == undefined || $('#' + e.id + "_form_html").length < 1) {
            layer.msg('缺少模板');
            return false;
        }
        $.get(e.url, e.data, function (res) {
            if (res.status) {
                if (typeof (res.data) !== 'object') {
                    layer.msg('接口数据错误');
                    return false;
                }
                var content = $('#' + e.id + "_form_html").html();
                laytpl(content).render(res.data, function (reshtml) {
                    if (e.opentype == 'layer.open') {
                        layer.open({
                            id: e.id + '_form_box',
                            type: 1,
                            anim: 4,
                            area: e.area,
                            title: e.title,
                            maxmin: e.maxmin,
                            offset: e.offset,
                            content: reshtml,
                            resize: e.resize,
                            btn: ['确定', '取消'],
                            yes: function (index, layero) {
                                $('#' + e.id + '_form_btn_save').click();
                            },
                            success: function (layero, index) {
                                if (e.overflow === true) $('#' + e.id + '_form_box').css('overflow', 'visible');
                                (typeof e.callbefore === 'function') && e.callbefore(layero, index, res);
                                (typeof e.getdata === 'function') && e.getdata(res);
                                form.render(null, e.id + '_form_lay_filter');//固度表单 id名 + '_form_lay_filter'
                                //固定提交按钮 id + _form_btn_save
                                form.on('submit(' + e.id + '_form_btn_save' + ')', function (data) {
                                    if (typeof e.postbefore === 'function') {
                                        data.field = e.postbefore(data.field);
                                    }
                                    if (data.field === false) return false;
                                    var formobj = {
                                        type: 'POST',
                                        encode: e.encode ? e.encode : 0,
                                        url: e.url,
                                        data: data.field,
                                        success: function (res2) {
                                            if (res2.status) {
                                                layer.msg(res2.msg, { time: 1300 }, function () {
                                                    e.tablelayid && table.reloadData(e.tablelayid);
                                                    layer.close(index);
                                                });
                                            } else {
                                                layer.msg(res2.msg);
                                            }
                                            (typeof e.callback === 'function') && e.callback(res2);
                                        }
                                    };
                                    $.ajax(formobj);
                                    return false;
                                });
                            }
                        });
                    } else if (e.opentype == 'dom') {
                        $('#' + e.box).empty().append(reshtml);
                        (typeof e.callbefore === 'function') && e.callbefore(res);
                        (typeof e.getdata === 'function') && e.getdata(res);
                        form.render(null, e.id + '_form_lay_filter');
                        form.on('submit(' + e.id + '_form_btn_save' + ')', function (data) {
                            if (typeof e.postbefore === 'function') {
                                data.field = e.postbefore(data.field);
                            }
                            if (data.field === false) return false;
                            $.ajax({
                                type: 'POST',
                                encode: e.encode ? e.encode : 0,
                                url: e.url,
                                data: data.field,
                                success: function (res2) {
                                    if (res2.status) {
                                        layer.msg(res2.msg, { time: 1300 }, function () {
                                            e.tablelayid && table.reloadData(e.tablelayid);
                                        });
                                    } else {
                                        layer.msg(res2.msg);
                                    }
                                    (typeof e.callback === 'function') && e.callback(res2);
                                }
                            });
                            return false;
                        });
                    }
                });
            } else {
                layer.msg(res.msg);
                return false;
            }
        });
        return t;
    };

    /**查看，通用处理方法 tpl，默认配置与form 一致*/
    kaige.prototype.details = function (e) {
        var t = this;
        e = $.extend(t.config().form, e);
        if (e.id == undefined || $('#' + e.id + "_form_html").length < 1) {
            layer.msg('缺少模板');
            return false;
        }
        $.get(e.url, e.data, function (res) {
            if (res.status) {
                if (typeof (res.data) !== 'object') {
                    layer.msg('接口数据错误');
                    return false;
                }
                var content = $('#' + e.id + "_form_html").html();
                laytpl(content).render(res.data, function (reshtml) {
                    if (e.opentype == 'layer.open') {
                        layer.open({
                            id: e.id + '_form_box',
                            type: 1,
                            anim: 4,
                            area: e.area,
                            title: e.title,
                            maxmin: e.maxmin,
                            content: reshtml,
                            btn: ['确定', '取消'],
                            yes: function (index, layero) {
                                layer.close(index);
                            },
                            success: function (layero, index) {
                                if (e.overflow) $('#' + e.id + '_form_box').css('overflow', 'visible');
                                (typeof e.callbefore === 'function') && e.callbefore(layero, index);
                                (typeof e.getdata === 'function') && e.getdata(res);
                                form.render(null, e.id + '_form_lay_filter');//固度表单 id名 + '_form_lay_filter'
                                // 查看是没有再提交的，有需要直接写在 callback;
                                (typeof e.callback === 'function') && e.callback(layero, index); // 这里传出 layer.open 的对象与窗口索引
                            }
                        });
                    } else if (e.opentype == 'dom') {
                        $('#' + e.box).html(reshtml);
                        (typeof e.callbefore === 'function') && e.callbefore();
                        (typeof e.getdata === 'function') && e.getdata(res);
                        form.render(null, e.id + '_form_lay_filter');
                        (typeof e.callback === 'function') && e.callback();
                    }
                });
            } else {
                layer.msg(res.msg);
                return false;
            }
        });
        return t;
    };

    /**删除，支持批量删除 */
    kaige.prototype.del = function (e) {
        var t = this;
        e = $.extend(t.config().del, e);
        var data = e.data;
        if (data.length <= 0) {
            layer.msg("请先选要操作的数据！");
            return t;
        }
        var ids = '';
        $.each(data, function (i, obj) {
            ids += obj.id + ',';
        });
        ids = ids.substring(0, ids.length - 1);
        layer.confirm('确认删除选中的数据吗？', {
            title: '<i class="layui-icon layui-icon-delete"></i> 删除确认',
            btn: ['确认', '取消']
        }, function () {
            $.post(e.url, { id: ids }, function (res) {
                res.status && (e.tablelayid && table.reloadData(e.tablelayid, {
                    page: {
                        curr: 1 //重新从第 1 页开始
                    }
                }, true));
                layer.msg(res.msg);
                (typeof e.callback === 'function') && e.callback(res);
            });
        });
        return t;
    }

    /**查看图片 */
    kaige.prototype.viewimage = function (e) {
        var t = this;
        e = $.extend(t.config().viewimage, e);
        if (e.url == undefined || e.url == '' || e.url == null) return t;
        layer.open({
            type: 1,
            title: false,
            closeBtn: 0,
            scrollbar: false,
            maxWidth: e.maxwidth,
            maxHeight: e.maxheight,
            skin: 'layui-layer-nobg', //没有背景色
            shadeClose: true,
            content: "<img style='max-width:" + e.maxwidth + "px;max-height:" + e.maxheight + "px;' src='" + e.url + "' alt=''>",
        });
        return t;
    }

    /**
     * 上传文件P2P交互(赋值)
     * @后台得到 id,name,url,ext,type
     */
    kaige.prototype.file_info = function (d) {
        if (d) {
            var src = d.url ? d.url : (d.src ? d.src : '');
            $(d.inputid).val(d.id);
            $(d.imgid).attr('src', src);
            layer.close(window.file_win_layid);
        }
    }

    /**表单里多个字段需要上传文件的 */
    kaige.prototype.upload_multi_files = function (d) {
        if (d) {
            $(d.btn).on('click', function (ev) {
                window.file_win_layid = layer.open({
                    type: 2,
                    title: '<i class="fa fa-upload"></i> 上传文件',
                    shade: 0.5,
                    area: ['90%', '90%'],
                    content: d.url,
                    success: function (layero, index) {
                        // 交互方法，如有自定义就使用自定义的，如果没有就使用默认的
                        if (typeof d.file_info === 'function') {
                            d.file_info();
                        } else {
                            window.file_info = function (opt) {
                                if (opt) {
                                    var src = opt.url ? opt.url : (opt.src ? opt.src : '');
                                    kaige.file_info({
                                        inputid: d.input_id,
                                        imgid: d.img_id,
                                        id: opt.id,
                                        url: src
                                    });
                                }
                            };
                        }
                        //回调
                        if (typeof d.callback === 'function') {
                            d.callback();
                        }
                    }
                });
            });
        }
    }

    /**加载表格列表 */
    kaige.prototype.table = function (e) {
        var t = this;
        e = $.extend(t.config().table, e);
        table.render(e);
    }

    /**
     * 选择框 页面需要 加载 xmSelect.js
     * @param {} e 
     * @returns 
     */
    kaige.prototype.xmSelect = function (e) {
        if (typeof (xmSelect) !== 'object') {
            layer.msg('未加载xmSelect.js');
            return false;
        }
        var t = this;
        e = $.extend(t.config().xmSelect, e);
        //dom名称关系不能乱.
        var input_elm = '#' + e.id;
        var select_elm = input_elm + '_select_box';
        var input_name_elm = input_elm + '_name';
        var obj = $(input_elm), in_obj = $(input_name_elm);
        if (obj.length < 1) {
            return false;
        }
        setTimeout(function () {
            var xsopt = {
                el: select_elm,
                theme: e.theme,
                filterable: e.filterable,
                data: [],
                radio: e.radio || false,
                clickClose: e.clickClose || false,
                on: function (reson) {
                    var id = '', name = '';
                    if (e.radio) {
                        id = reson.arr.length > 0 ? reson.arr[0].value : '';
                        name = reson.arr.length > 0 ? reson.arr[0].name : '';
                    } else {
                        layui.each(reson.arr, function (index, item) {
                            if (index > 0) {
                                id += ',', name += ',';
                            }
                            id += item.value;
                            name += item.name;
                        });
                    }
                    obj.val(id);
                    in_obj.val(name);
                },
                remoteSearch: e.remoteSearch,
                remoteMethod: function (val, cb, show) {
                    var where = e.udata;
                    where.keywords = val;
                    $.ajax({
                        type: 'GET',
                        async: false, // 异步
                        url: e.url,
                        data: where,
                        success: function (res) {
                            // 处理 数据格式
                            if (res.code == 0) {
                                var data9 = [];
                                var old_value = obj.val();
                                layui.each(res.data, function (index5, item5) {
                                    data9.push({
                                        'name': (item5.name ? item5.name : item5.real_name),
                                        'value': item5.id,
                                        'selected': strIn(item5.id.toString(), old_value)
                                    });
                                });
                                cb(data9);
                            } else {
                                cb([]);
                            }
                        }
                    });
                },
            };
            if (typeof (e.model) === 'object') {
                xsopt.model = e.model;
            } else {
                if (e.radio === true) {
                    xsopt.model = {
                        label: {
                            type: 'text',
                            text: {
                                //左边拼接的字符
                                left: '',
                                //右边拼接的字符
                                right: '',
                                //中间的分隔符
                                separator: ', ',
                            },
                        }
                    };
                }
            }
            if (e.disabled === true) {
                xsopt.disabled = e.disabled;
            }
            xmSelect.render(xsopt);
        }, 200);
    }

    /**
     * 选择框树型 页面需要 加载 xmSelect.js
     * @param {} e 
     * @returns 
     */
    kaige.prototype.xmSelectTree = function (e) {
        if (typeof (xmSelect) !== 'object') {
            layer.msg('未加载xmSelect.js');
            return false;
        }
        var t = this;
        e = $.extend(t.config().xmSelect, e);
        //dom名称关系不能乱.
        var input_elm = '#' + e.id;
        var select_elm = input_elm + '_select_box';
        var input_name_elm = input_elm + '_name';
        var obj = $(input_elm), in_obj = $(input_name_elm);
        if (obj.length < 1) {
            return false;
        }
        $.ajax({
            type: 'GET',
            async: false, // 异步
            url: e.url,
            data: e.udata || {},
            success: function (res) {
                // 处理 数据格式
                if (res.code == 0) {
                    var data9 = [];
                    var old_value = obj.val();
                    data9 = treeSelected(res.data, old_value);
                    cb(data9);
                } else {
                    cb([]);
                }
            }
        });
        function cb(data) {
            var xsopt = {
                el: select_elm,
                data: data,
                radio: e.radio || false,
                clickClose: e.clickClose || false,
                tree: {
                    show: e.tree.show || true,
                    strict: e.tree.strict || false,
                    expandedKeys: e.tree.expandedKeys || true,
                    clickCheck: e.tree.clickCheck || true,
                },
                direction: 'auto',
                toolbar: {
                    show: true,
                },
                filterable: true,
                paging: true,
                on: function (reson) {
                    var id = '', name = '';
                    if (e.radio) {
                        id = reson.arr.length > 0 ? reson.arr[0].value : '';
                        name = reson.arr.length > 0 ? reson.arr[0].name : '';
                    } else {
                        layui.each(reson.arr, function (index, item) {
                            if (index > 0) {
                                id += ',', name += ',';
                            }
                            id += item.value;
                            name += item.name;
                        });
                    }
                    obj.val(id);
                    in_obj.val(name);
                    (typeof e.callback === 'function') && e.callback({ id: id, name: name });
                },
            };
            if (typeof (e.style) === 'object') {
                xsopt.style = e.style;
            }
            if (typeof (e.tips) === 'string') {
                xsopt.tips = e.tips;
            }
            if (typeof (e.model) === 'object') {
                xsopt.model = e.model;
            } else {
                if (e.radio === true) {
                    xsopt.model = {
                        label: {
                            type: 'text'
                        }
                    };
                }
            }
            xmSelect.render(xsopt);
            (typeof e.lastback === 'function') && e.lastback(xsopt);
        };
    }

    /**流程专用表单*/
    kaige.prototype.flowform = function (e) {
        var t = this;
        e = $.extend(t.config().form, e);
        if (e.id == undefined || kaige_form_Tpl === undefined || $('#' + e.id + "_edit_form_box").length < 1) {
            layer.msg('缺少模板');
            return false;
        }
        $.get(e.url, e.data, function (res) {
            if (res.status) {
                if (typeof (res.data) !== 'object') {
                    layer.msg('接口数据错误');
                    return false;
                }
                var content = kaige_form_Tpl;
                content = content.replace('<mtl>chaosong</mtl>', e.chaosong);
                content = content.replace('<mtl>btnfoot</mtl>', e.btnfoot);
                var lodata = res.data;
                laytpl(content).render(lodata, function (reshtml) {
                    $('#' + e.id + "_edit_form_box").empty().append(reshtml);
                    (typeof e.callbefore === 'function') && e.callbefore(res);
                    form.render(null, e.id + '_form_lay_filter');
                    //保存
                    form.on('submit(' + e.id + '_form_btn_save' + ')', function (data) {
                        if (typeof e.postbefore === 'function') {
                            data.field = e.postbefore(data.field);
                        }
                        if (data.field === false) return false;
                        $.ajax({
                            type: 'POST',
                            encode: e.encode ? e.encode : 0,
                            url: e.url,
                            data: data.field,
                            success: function (res2) {
                                layer.msg(res2.msg, { time: 1300 }, function () {
                                    if (res2.status && e.tablelayid) parent.layui.table.reloadData(e.tablelayid);
                                });
                                (typeof e.callback === 'function') && e.callback(res2);
                                setTimeout(function () { closeplSelf(); }, 1500);
                            }
                        });
                        return false;
                    });
                    function closeplSelf() {
                        var layerobj = parent.$('#kaige_open_page').parent();
                        if (typeof (layerobj) === "object") {
                            var lindex = layerobj.attr('times');
                            parent.layui.layer.close(lindex);
                        }
                        layerobj = parent.$('#szoa_open_id_10_14_12').parent();
                        if (typeof (layerobj) === "object") {
                            var lindex = layerobj.attr('times');
                            parent.layui.layer.close(lindex);
                        }
                        layerobj = parent.$('#szoa_open_id_10_14_11').parent();
                        if (typeof (layerobj) === "object") {
                            var lindex = layerobj.attr('times');
                            parent.layui.layer.close(lindex);
                        }
                    }
                    var btn1 = $('#' + e.id + '_form_btn_yes'), btn2 = $('#' + e.id + '_form_btn_draft'), btn3 = $('#' + e.id + '_form_btn_revocation');
                    //保存并提交
                    btn1.on('click', function (ev) {
                        $('#kaige_is_put').val(1); //为1 直接提交流程
                        $('#' + e.id + '_form_btn_save').click();
                    });
                    //保存为草稿
                    btn2.on('click', function (ev) {
                        $('#kaige_is_put').val(2); //草稿
                        $('#' + e.id + '_form_btn_save').click();
                    });
                    //撤回
                    btn3.on('click', function (ev) {
                        $.ajax({
                            type: 'POST',
                            url: e.url,
                            data: { id: $('input[name=id]').val(), is_put: 3 },
                            success: function (res2) {
                                layer.msg(res2.msg, { time: 1300 }, function () {
                                    if (res2.status && e.tablelayid) parent.layui.table.reloadData(e.tablelayid);
                                });
                                setTimeout(function () { closeplSelf(); }, 1500);
                            }
                        });
                        return false;
                    });
                    //取消
                    $('#' + e.id + '_form_btn_cancel').on('click', function (ev) {
                        closeplSelf();
                    });

                    // 已经提交 不能再编辑，但可以撤回
                    if (typeof (lodata.is_put) === 'number' && lodata.is_put == 1 && typeof (lodata.status) === 'number' && lodata.status == 1) {
                        btn1.hide();
                        btn2.hide();
                        btn3.show();
                    } else {
                        btn1.show();
                        btn2.show();
                        btn3.hide();
                    }
                    if (typeof (lodata.status) === 'number' && lodata.status > 1) {
                        btn1.empty().remove();
                        btn2.empty().remove();
                        btn3.empty().remove();
                    }
                });
            } else {
                layer.msg(res.msg);
                return false;
            }
        });
        return t;
    };

    /**流程查看渲染*/
    kaige.prototype.flowrender = function (e) {
        var t = this;
        e = $.extend(t.config().form, e);
        if (e.id == undefined || $('#' + e.id + "_form_html").length < 1 || kaige_look_table_Tpl == undefined || $('#' + e.id + "_html_box").length < 1) {
            layer.msg('缺少模板');
            return false;
        }
        $.get(e.url, e.data, function (res) {
            if (res.status) {
                if (typeof (res.data) !== 'object') {
                    layer.msg('接口数据错误');
                    return false;
                }
                var content = $('#' + e.id + "_form_html").html();
                content = content.replace('<mpl>kaige_look_table_Tpl</mpl>', kaige_look_table_Tpl);
                laytpl(content).render(res.data, function (reshtml) {
                    $('#' + e.id + "_html_box").empty().append(reshtml);
                    (typeof e.callbefore === 'function') && e.callbefore(res);
                    form.render(null, e.id + '_form_lay_filter');//固度表单 id名 + '_form_lay_filter'
                    // 查看是没有再提交的，有需要直接写在 callback;
                    (typeof e.callback === 'function') && e.callback(res);
                });
            } else {
                layer.msg(res.msg);
                return false;
            }
        });
        return t;
    };

    kaige.prototype.open = function (e) {
        var koindex = layer.open({
            id: e.id + '_open_page',
            type: 2,
            anim: 2,
            area: e.area || ['90%', '83%'],
            title: e.title || false,
            maxmin: !e.maxmin,
            content: e.url,
            offset: '50px',
            success: function (layero, index) {
                layero.find('.layui-layer-min').remove(); //去掉最小化按钮
                (typeof e.callback === 'function') && e.callback(layero, index);
            }
        });
        return koindex;
    }

    kaige.prototype.tableSelect = function (e) {
        var t = this;
        e = $.extend(t.config().form, e);
        var obj = $('#' + e.id);
        if (e.id == undefined || obj.length < 1) {
            layer.msg('缺少DOM');
            return false;
        }
        layui.tableSelect.render({
            elem: '#' + e.id + '_name',
            searchKey: e.searchKey || 'keywords',
            checkedKey: e.checkedKey || 'id',
            table: {
                url: e.url,
                cols: e.cols,
                where: e.where
            },
            done: function (elem, data) {
                if (typeof (e.done) === 'function') {
                    e.done(elem, data);
                } else {
                    var names = [], ids = [];
                    layui.each(data.data, function (index, item) {
                        if (item.name) {
                            names.push(item.name);
                        } else if (item.real_name) {
                            names.push(item.real_name);
                        }
                        ids.push(item.id);
                    })
                    elem.val(names.join(","));
                    obj.val(ids.join(","));
                }
            }
        });
    }

    var kaige = new kaige();
    exports(MOD_NAME, kaige)
});